package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class AutoFillAspect {

    //切入点
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut(){}

    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("开始进行数据填充");
        //1.获取拦截类型
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType value = autoFill.value();
        //2.获取请求参数
        Object[] args = joinPoint.getArgs();
        if(args == null || args.length == 0) return;
        Object o = args[0];
        //3.设置创建时间、更新时间，创建人、更新人
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        //4.为字段赋值
        Class oClass = o.getClass();//获取参数的类
        //获取对应的方法
        Method setCreateTime = oClass.getDeclaredMethod("setCreateTime", LocalDateTime.class);
        Method setUpdateTime = oClass.getDeclaredMethod("setUpdateTime", LocalDateTime.class);
        Method setCreateUser = oClass.getDeclaredMethod("setCreateUser", Long.class);
        Method setUpdateUser = oClass.getDeclaredMethod("setUpdateUser", Long.class);
        if(value == OperationType.INSERT){
            //为4个字段赋值
            setCreateUser.invoke(o,currentId);
            setCreateTime.invoke(o,now);
            setUpdateUser.invoke(o,currentId);
            setUpdateTime.invoke(o,now);
        } else if (value == OperationType.UPDATE) {
            setUpdateUser.invoke(o,currentId);
            setUpdateTime.invoke(o,now);
        }
    }

}
